const api = require('../../../utils/api.js');

Page({
  data: {
    currentStep: 1,
    totalSteps: 4,
    // 基本信息
    gender: '',
    age: '',
    // 身体数据
    height: '',
    weight: '',
    // 生活习惯
    activityLevelIndex: 0,
    activityLevels: [
      { value: 1.2, text: '久坐少动' },
      { value: 1.375, text: '轻度运动（每周1-3次）' },
      { value: 1.55, text: '中度运动（每周3-5次）' },
      { value: 1.725, text: '重度运动（每周6-7次）' },
      { value: 1.9, text: '专业运动员' }
    ],
    dietPreferenceIndex: 0,
    dietPreferences: [
      { value: 'normal', text: '均衡饮食' },
      { value: 'vegetarian', text: '素食主义' },
      { value: 'lowCarb', text: '低碳水饮食' },
      { value: 'highProtein', text: '高蛋白饮食' }
    ],
    // 健康目标
    healthGoals: [
      { id: 1, text: '减重塑形', icon: '/images/goals/weight-loss.png', selected: false },
      { id: 2, text: '增肌增重', icon: '/images/goals/muscle-gain.png', selected: false },
      { id: 3, text: '保持健康', icon: '/images/goals/health.png', selected: false },
      { id: 4, text: '改善睡眠', icon: '/images/goals/sleep.png', selected: false },
      { id: 5, text: '增强免疫力', icon: '/images/goals/immune.png', selected: false },
      { id: 6, text: '改善胃肠道', icon: '/images/goals/digestion.png', selected: false }
    ]
  },

  // 选择性别
  selectGender(e) {
    const gender = e.currentTarget.dataset.gender;
    this.setData({ gender });
  },

  // 输入年龄
  inputAge(e) {
    let age = e.detail.value;
    // 限制年龄范围
    if (age > 120) age = 120;
    this.setData({ age });
  },

  // 输入身高
  inputHeight(e) {
    let height = e.detail.value;
    // 限制身高范围
    if (height > 250) height = 250;
    this.setData({ height });
  },

  // 输入体重
  inputWeight(e) {
    let weight = e.detail.value;
    // 限制体重范围
    if (weight > 200) weight = 200;
    this.setData({ weight });
  },

  // 选择活动水平
  selectActivityLevel(e) {
    this.setData({
      activityLevelIndex: e.detail.value
    });
  },

  // 选择饮食偏好
  selectDietPreference(e) {
    this.setData({
      dietPreferenceIndex: e.detail.value
    });
  },

  // 切换健康目标
  toggleGoal(e) {
    const goalId = e.currentTarget.dataset.id;
    const goals = this.data.healthGoals.map(goal => {
      if (goal.id === goalId) {
        return { ...goal, selected: !goal.selected };
      }
      return goal;
    });
    this.setData({ healthGoals: goals });
  },

  // 验证当前步骤数据
  validateCurrentStep() {
    const { currentStep, gender, age, height, weight, healthGoals } = this.data;
    
    switch (currentStep) {
      case 1:
        if (!gender) {
          wx.showToast({
            title: '请选择性别',
            icon: 'none'
          });
          return false;
        }
        if (!age || age < 1) {
          wx.showToast({
            title: '请输入有效年龄',
            icon: 'none'
          });
          return false;
        }
        break;
      
      case 2:
        if (!height || height < 50) {
          wx.showToast({
            title: '请输入有效身高',
            icon: 'none'
          });
          return false;
        }
        if (!weight || weight < 20) {
          wx.showToast({
            title: '请输入有效体重',
            icon: 'none'
          });
          return false;
        }
        break;
      
      case 4:
        const selectedGoals = healthGoals.filter(goal => goal.selected);
        if (selectedGoals.length === 0) {
          wx.showToast({
            title: '请至少选择一个健康目标',
            icon: 'none'
          });
          return false;
        }
        break;
    }
    
    return true;
  },

  // 下一步
  nextStep() {
    if (!this.validateCurrentStep()) return;
    
    if (this.data.currentStep < this.data.totalSteps) {
      this.setData({
        currentStep: this.data.currentStep + 1
      });
    }
  },

  // 上一步
  prevStep() {
    if (this.data.currentStep > 1) {
      this.setData({
        currentStep: this.data.currentStep - 1
      });
    }
  },

  // 提交评估
  submitAssessment() {
    if (!this.validateCurrentStep()) return;

    const {
      gender, age, height, weight,
      activityLevels, activityLevelIndex,
      dietPreferences, dietPreferenceIndex,
      healthGoals
    } = this.data;

    const assessmentData = {
      gender,
      age: parseInt(age),
      height: parseFloat(height),
      weight: parseFloat(weight),
      activityLevel: activityLevels[activityLevelIndex].value,
      dietPreference: dietPreferences[dietPreferenceIndex].value,
      healthGoals: healthGoals.filter(goal => goal.selected).map(goal => goal.id)
    };

    wx.showLoading({
      title: '提交中...',
      mask: true
    });

    api.submitHealthAssessment(assessmentData).then(res => {
      wx.hideLoading();
      
      if (res.code === 200) {
        wx.showToast({
          title: '评估完成',
          icon: 'success',
          duration: 2000,
          success: () => {
            setTimeout(() => {
              // 返回营养定制主页
              wx.navigateBack();
            }, 2000);
          }
        });
      } else {
        wx.showToast({
          title: res.msg || '提交失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      });
    });
  }
}); 